<?php

namespace app\api\controller\user;

use think\Controller;
use think\Request;

class Auth extends Controller
{
    public function __construct()
    {
        parent::__construct();

        $this->UserModel = model('User.User');
        $this->RegionModel = model('Region');
    }

    //授权登录
    public function login()
    {
        if ($this->request->isPost()) {
            $code = $this->request->param('code', '');

            if (!$code) {
                $this->error('临时授权失败');
                exit;
            }

            //调用微信接口
            $result = $this->code2ession($code);

            $openid = isset($result['openid']) ? trim($result['openid']) : '';

            if (empty($openid)) {
                $this->error('微信授权失败');
                exit;
            }

            //根据openid判断是否有绑定用户,有绑定用户就将用户信息返回,没绑定就去绑定
            $User = $this->UserModel->where(['openid' => $openid])->find();

            //找到了用户
            if ($User) {
                $data = [
                    'id' => $User['id'],
                    'openid' => $User['openid'],
                    'email' => $User['email'],
                    'nickname' => $User['nickname'],
                    'avatar' => $User['avatar_cdn'],
                    'sex' => $User['sex'],
                    'sex_text' => $User['sex_text'],
                    'province' => $User['province'],
                    'city' => $User['city'],
                    'district' => $User['district'],
                    'createtime' => $User['createtime'],
                    'content' => $User['content'],
                    'point' => $User['point'],
                    'vip' => $User['vip'],
                    'auth' => $User['auth'],
                    'cover' => $User['cover_cdn'],
                    'region' => explode('-', $User['region']),
                    'region_text' => $User['region']
                ];

                $this->success('登录成功', null, $data);
                exit;
            } else {
                //授权是成功的,只是没有关联用户
                $this->success('请先关联账号', '/pages/user/bind', null);
                exit;
            }
        }
    }

    //微信小程序绑定,如果不存在就注册,如果存在就绑定
    public function bind()
    {
        if ($this->request->isPost()) {
            $code = $this->request->param('code', '');

            if (!$code) {
                $this->error('临时授权失败');
                exit;
            }

            $password = $this->request->param('password', '');

            if (empty($password)) {
                $this->error('密码不能为空');
                exit;
            }

            //调用微信接口
            $result = $this->code2ession($code);

            $openid = isset($result['openid']) ? trim($result['openid']) : '';

            if (empty($openid)) {
                $this->error('微信授权失败');
                exit;
            }

            //根据openid判断是否有绑定用户,有绑定用户就将用户信息返回,没绑定就去绑定
            $User = $this->UserModel->where(['openid' => $openid])->find();

            if ($User) {
                $data = [
                    'id' => $User['id'],
                    'openid' => $User['openid'],
                    'email' => $User['email'],
                    'nickname' => $User['nickname'],
                    'avatar' => $User['avatar_cdn'],
                    'sex' => $User['sex'],
                    'sex_text' => $User['sex_text'],
                    'province' => $User['province'],
                    'city' => $User['city'],
                    'district' => $User['district'],
                    'createtime' => $User['createtime'],
                    'content' => $User['content'],
                    'point' => $User['point'],
                    'vip' => $User['vip'],
                    'auth' => $User['auth'],
                    'cover' => $User['cover_cdn'],
                    'region' => explode('-', $User['region']),
                    'region_text' => $User['region']
                ];
                $this->success('您已经绑定过,无需重新绑定');
                exit;
            }

            //用户不存在
            $email = $this->request->param('email', '');

            if (empty($email)) {
                $this->error('请填写邮箱地址');
                exit;
            }

            //判断邮箱是否存在
            $check = $this->UserModel->where(['email' => $email])->find();

            if ($check) {
                //人已经找到了，先判断是否被绑定过，是判断密码是否正确，更新语句 openid
                if (!empty($check['openid'])) {
                    $this->error('您输入的邮箱用户已被绑定,无法再次绑定');
                    exit;
                }

                //密码盐
                $salt = $check['salt'];

                $repass = md5($password . $salt);

                if ($repass != $check['password']) {
                    $this->error('你绑定的账号密码输入错误');
                    exit;
                }

                //组装数据
                $data = [
                    'id' => $check['id'],
                    'openid' => $openid
                ];

                $result = $this->UserModel->isUpdate(true)->save($data);

                if ($result === FALSE) {
                    $this->error($this->UserModel->getError());
                    exit;
                }

                //重新查询最新的数据返回
                $check = [
                    'id' => $check['id'],
                    'openid' => $check['openid'],
                    'email' => $check['email'],
                    'nickname' => $check['nickname'],
                    'avatar' => $check['avatar_cdn'],
                    'sex' => $check['sex'],
                    'sex_text' => $check['sex_text'],
                    'province' => $check['province'],
                    'city' => $check['city'],
                    'district' => $check['district'],
                    'createtime' => $check['createtime'],
                    'content' => $check['content'],
                    'point' => $check['point'],
                    'vip' => $check['vip'],
                    'auth' => $check['auth'],
                    'cover' => $check['cover_cdn'],
                    'region' => explode('-', $check['region']),
                    'region_text' => $check['region'],
                ];
                $this->success('绑定成功', null, $data);
                exit;
            } else {
                //生成密码盐
                $salt = build_ranstr(10);

                //将密码和密码盐md5加密
                $password = md5(trim($password) . $salt);

                //获取系统配置表里面的赠送积分
                $RegisterPoint = model('Config')->where(['key' => 'RegisterPoint'])->value('value');

                //判断一下注册积分是不是一个整数
                $RegisterPoint = is_numeric($RegisterPoint) ? abs($RegisterPoint) : 0;

                //组装数据
                $data = [
                    'email' => $email,
                    'password' => $password,
                    'salt' => $salt,
                    'nickname' => $email,
                    'point' => $RegisterPoint,
                    'vip' => 0,
                    'auth' => 0,
                    'openid' => $openid
                ];

                //开始插入数据库
                $result = $this->UserModel->validate('common/user/User')->save($data);

                if ($result === FALSE) {
                    //注册失败
                    //getError 返回操作的结果
                    $this->error($this->UserModel->getError());
                    exit;
                } else {
                    $User = $this->UserModel->where(['openid' => $openid])->find();

                    $data = [
                        'id' => $User['id'],
                        'openid' => $User['openid'],
                        'email' => $User['email'],
                        'nickname' => $User['nickname'],
                        'avatar' => $User['avatar_cdn'],
                        'sex' => $User['sex'],
                        'sex_text' => $User['sex_text'],
                        'province' => $User['province'],
                        'city' => $User['city'],
                        'district' => $User['district'],
                        'createtime' => $User['createtime'],
                        'content' => $User['content'],
                        'point' => $User['point'],
                        'vip' => $User['vip'],
                        'auth' => $User['auth'],
                        'cover' => $User['cover_cdn'],
                        'region' => explode('-', $User['region']),
                        'region_text' => $User['region']
                    ];

                    //注册成功,跳转到登录界面
                    $this->success('注册并绑定成功', null, $data);
                    exit;
                }
            }
        }
    }

    //基本资料修改
    public function profile()
    {
        if ($this->request->isPost()) {
            $params = $this->request->param();

            //获取用户id
            $userid = $this->request->param('userid', 0);

            //判断用户是否存在
            $user = $this->UserModel->find($userid);

            if (!$user) {
                $this->error('用户不存在');
                exit;
            }

            //查询昵称是否已经存在(数据表昵称字段唯一索引)
            $nickname = $this->UserModel->where(['nickname' => $params['nickname']])->find();

            if ($nickname && $nickname['id'] != $userid) {
                $this->error('该昵称已存在');
                exit;
            }

            //组装数据
            $data = [
                'id' => $userid,
                'nickname' => $params['nickname'],
                'sex' => $params['sex'],
                'content' => $params['content']
            ];

            //获取城市信息
            $region = $this->request->param('region', '');

            if (!empty($region)) {
                //查询地区数据
                $parentpath = $this->RegionModel->where(['code' => $region])->value('parentpath');

                if (empty($parentpath)) {
                    $this->error('你所在的地区不存在,请重新选择');
                    exit;
                }

                //将字符串转化为数组
                $path = explode(',', $parentpath);

                if ($path < 0) {
                    $this->error('你所在的地区不存在,请重新选择');
                    exit;
                }

                if (isset($path[0])) {
                    $data['province'] = $path[0];
                }

                if (isset($path[1])) {
                    $data['city'] = $path[1];
                }

                if (isset($path[2])) {
                    $data['district'] = $path[2];
                }
            }

            //封面
            if (isset($_FILES['cover']) && $_FILES['cover']['size'] > 0) {
                $result = upload('cover');

                if ($result === FALSE) {
                    $this->error('上传封面图片失败');
                    exit;
                }

                //追加封面
                $data['cover'] = $result;
            }

            //更新数据库
            $result = $this->UserModel->isUpdate(true)->save($data);


            if ($result === FALSE) {

                //说明更新失败,但是你上传的图片是不能要的,直接删除
                @is_file($data['cover']) && @unlink($data['cover']);

                $this->error('修改个人资料失败');
                exit;
            } else {
                //先判断是否有选择新的图片
                if (@is_file($data['cover'])) {
                    //修改成功后,将原来的旧图片删除
                    $cover = ltrim($user['cover'], '/');
                    @is_file($cover) && @unlink($cover);
                }

                //直接查询最新的结果在返回
                $UserData = $this->UserModel->find($userid);
                $data = [
                    'id' => $UserData['id'],
                    'openid' => $UserData['openid'],
                    'email' => $UserData['email'],
                    'nickname' => $UserData['nickname'],
                    'avatar' => $UserData['avatar_cdn'],
                    'sex' => $UserData['sex'],
                    'sex_text' => $UserData['sex_text'],
                    'province' => $UserData['province'],
                    'city' => $UserData['city'],
                    'district' => $UserData['district'],
                    'createtime' => $UserData['createtime'],
                    'content' => $UserData['content'],
                    'point' => $UserData['point'],
                    'vip' => $UserData['vip'],
                    'auth' => $UserData['auth'],
                    'cover' => $UserData['cover_cdn'],
                    'region' => explode('-', $UserData['region']),
                    'region_text' => $UserData['region']
                ];

                $this->success('修改资料成功', null, $data);
                exit;
            }
        }
    }

    //调用微信的接口
    //js_code 登录临时凭证code参数
    protected function code2ession($js_code = null)
    {
        if ($js_code) {
            //appid
            $appid = 'wx95962ccadfb6596e';

            //密钥
            $secret = 'e8791ffc3eced56a7a7fcf133cdc1a04';

            //接口
            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$js_code&grant_type=authorization_code";


            //发起get请求
            $result = $this->https_request($url);

            //获取结果 将json转换为数组
            $resultArr = json_decode($result, true);

            return $resultArr;
        } else {
            return false;
        }
    }

    //http请求 利用php curl扩展去发送get 或者 post请求 服务器上面一定要开启 php curl扩展
    protected function https_request($url, $data = null)
    {
        if (function_exists('curl_init')) {
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
            if (!empty($data)) {
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($curl);
            curl_close($curl);
            return $output;
        } else {
            return false;
        }
    }
}
